import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { Ajax } from '../../api/api';
import MyHead from '../../components/MyHead';
import { changeCount } from '../../rtk/modules/data';
import { Swiper, Image, List, Ellipsis, PullToRefresh, InfiniteScroll } from 'antd-mobile'
import './index.scss'
import { Link } from 'react-router-dom';
import GList from '../../components/GList';
import { sleep } from 'antd-mobile/es/utils/sleep'
import { ShowMsg } from '../../utils/message';

const Home = () => {
    const dispatch = useDispatch()
    const count = useSelector((state: any) => state.data.count)
    const [banners, setBanners] = useState<any>([])
    const [goods, setGoods] = useState<any>([])

    const [options, setOptions] = useState<any>({
        pageNo: 1,
        pageSize: 10,
        total: 0
    })

    const getBanner = async () => {
        let res: any = await Ajax.goodbanners({
            limit: 4,
            skip: 20
        })
        if (res.code == 200) {
            setBanners(res.result)
        }
    }

    const getGoodsList = async () => {
        let res: any = await Ajax.getgoods(options);
        const { code, result, pageNo, pageSize, total } = res;
        if (res.code == 200) {
            setGoods(res.result)
            setOptions({
                pageNo,
                pageSize,
                total
            })
        }
    }


    useEffect(() => {
        getBanner()
        getGoodsList()
    }, [])

    const [hasMore, setHasMore] = useState(true)

    const loadMore = async () => {
        await sleep(1000)
        options.pageNo++;
        setOptions({ ...options })
        let res: any = await Ajax.getgoods(options);
        const { code, result, pageNo, pageSize, total } = res;
        setGoods((val: any) => [...val, ...res.result])
        setHasMore(res.result.length > 0)

    }
    const onRefresh = async () => {
        await sleep(1000)
        goods.reverse()
        setGoods([...goods])
        ShowMsg('刷新数据成功')
    }
    return (
        <div className='home'>
            <MyHead title='首页' back={!!1} ></MyHead>
            <Swiper autoplay loop>
                {
                    banners.map((item: any, index: number) => (
                        <Swiper.Item key={index}>
                            <Image src={item.img} className='banner-img' style={{ width: '100%' }} />
                        </Swiper.Item>
                    ))
                }
            </Swiper>

            <PullToRefresh
                onRefresh={onRefresh}
            >
                <GList goods={goods} ></GList>
                <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
            </PullToRefresh>
        </div>
    )
}

export default Home